package cn.zhys513.mk.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.zhys513.core.util.FileUtil;
import cn.zhys513.mk.view.BookView;
@Configuration
@RestController
@RequestMapping
public class BookController {
	
	@Value("${book.home}")
	String home;
	
	@Value("${book.summary}")
	String summary; 
 
	@RequestMapping(value={"/index","/","","/**.md","/**/*.md","/**.MD","/**/*.MD"})
	public ModelAndView content(HttpServletRequest request) throws Exception{
		String serverName = request.getServletPath() ;
		if("".equals(serverName) || "/".equals(serverName) ||"/index".equals(serverName))
			serverName = summary;  
		String path = home + serverName;
		String mkstr = FileUtil.read(path, "UTF-8");
		ModelAndView mav = new ModelAndView(BookView.BOOK); 
		mav.addObject("content", mkstr);
		mav.addObject("contentPath", serverName);
		return mav;
	}
	 
	@PostMapping(value={"/add"})
	public HashMap<String, String> add(HttpServletRequest request,String content,String contentPath) {
		String path = home + contentPath;
		FileUtil.write(path, content);
		HashMap<String, String> result = new HashMap<String, String>();
		result.put("code", "200");
		result.put("mes", "保存成功");
		return result;
	}
	
	 
}
